package com.ohs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ohs.mapper.before.UserMapper;
import com.ohs.pojo.User;
import com.ohs.service.UserService;
import com.ohs.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@Service
public class UserServiceImpl implements UserService {
    //注入持久层对象
    @Autowired(required=false)
    UserMapper userMapper;
    //根据邮箱查找当前用户信息
    @Override
    public ResponseResult findUserByEmail(String email) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email",email);
        User user = userMapper.selectOne(queryWrapper);
        if (user!=null){
            return new ResponseResult(201,"该邮箱已被注册");

        }
        return new ResponseResult(200,"邮箱可用");
    }

    //根据用户名查找当前用户信息
    @Override
    public ResponseResult findUserByName(String userName) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userName",userName);
        User user = userMapper.selectOne(queryWrapper);
        if (user!=null){
            return new ResponseResult(201,"该用户名已被注册");

        }
        return new ResponseResult(200,"用户名可用");
    }

    //注册
    @Override
    public ResponseResult doReg(User user, String confirmPwd, String code, HttpSession session) {
        String email = user.getEmail();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("email",email);
        User user1 = userMapper.selectOne(queryWrapper);
        if (user1 != null){
            return new ResponseResult(201,"用户已存在");
        }
        if (!user.getPassword().equals(confirmPwd)){
            return new ResponseResult(202,"密码不一致");
        }
        //取出验证码
        String emailCode = (String) session.getAttribute("eCode");
        if (!code.equals(emailCode)){
            return new ResponseResult(203,"验证码错误");
        }
        user.setModifyUser(user.getUserName());
        int row = userMapper.insert(user);
        if (row != 1){
            return new ResponseResult(204,"注册失败！");
        }
        return new ResponseResult(200,"注册成功！");
    }

    //用户名登录
    @Override
    public String doLogin(User user, String code, HttpSession session, Model model) {
        if (StringUtils.isEmpty(user.getPassword())){
            model.addAttribute("msg","密码必填");
            return "before/login";
        }
        if (StringUtils.isEmpty(code)){
            model.addAttribute("msg","验证码必填");
            return "before/login";
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userName",user.getUserName());
        //user1是数据库中已存在的用户
        User user1 = userMapper.selectOne(queryWrapper);
        if(user1==null){
            model.addAttribute("msg","查无此用户！");
            return "before/login";
        }
        //获取生成的验证码
        String code1 = (String)session.getAttribute("code");
        //无视大小写
        if (!code1.equalsIgnoreCase(code)){
            model.addAttribute("msg","验证码输入错误");
            return "before/login";
        }
        //判断密码是否正确
        if (!user.getPassword().equals(user1.getPassword())){
            model.addAttribute("msg","用户名或者密码错误");
            return "before/login";
        }
        //绑定可能用得上的session
        session.setAttribute("userName",user1.getUserName());
        session.setAttribute("userId",user1.getUserId());
        session.setAttribute("email",user1.getEmail());
        return "redirect:/";
    }

    //邮箱登录
    @Override
    public ResponseResult doEmailLogin(String email, String eCode ,HttpSession session) {
        if (StringUtils.isEmpty(email)){
            return new ResponseResult(201,"邮箱必填");
        }
        if (StringUtils.isEmpty(eCode)){
            return new ResponseResult(202,"验证码必填");
        }
        String realCode = (String) session.getAttribute("eCode");
        if (!realCode.equals(eCode)){
            return new ResponseResult(203,"验证码错误");
        }
        //根据页面输入的邮箱从数据库中取出该对象
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("email",email);
        User user = userMapper.selectOne(queryWrapper);
        if (user.getEmail()==null){
            return new ResponseResult(204,"查无此邮箱");
        }
        //绑定可能用得上的session
        session.setAttribute("userName",user.getUserName());
        session.setAttribute("userId",user.getUserId());
        session.setAttribute("email",user.getEmail());
        return new ResponseResult(200,"登陆成功!");
    }
    @Override
    public ResponseResult updateUser(User user,HttpSession session) {
        if(user ==null){
            return new ResponseResult(201,"用户名为空，请重新登录。");
        }
        Integer userId=(Integer) session.getAttribute("userId");
        user.setUserId(userId);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        int row=userMapper.updateById(user);
        if(row!=1){
            return new ResponseResult(202,"更新信息失败，请重新操作。");
        }
        return new ResponseResult(200,"更新信息成功，请继续操作。");
    }

    @Value("${web.upload-path}")
    private String uploadPath;
    @Override
    public ResponseResult doUpdateAvartar(MultipartFile file, HttpSession session) throws IOException {
        if(file==null){
            return new ResponseResult(201,"文件为空，请重新输入文件。");
        }
        if(file.getSize()>1024*1024*10){
            return new ResponseResult(202,"文件过大，请重新上传。");
        }
        String filename = file.getOriginalFilename();
        int index = filename.indexOf(".");
        String suffix =filename.substring(index);
        long time =System.currentTimeMillis();
        String newfilename = time+suffix;
        String path= session.getServletContext().getRealPath("upload");
        System.out.println(path);
        File file1 =new File(path);
        if(!file1.exists()){
            file1.mkdir();
        }
        String filePath=path+"/"+newfilename;
        /*File file2=new File(filePath);*/
        File file2=new File(uploadPath,newfilename);
        file.transferTo(file2);
        System.out.println(filePath);
        Integer userId=(Integer) session.getAttribute("userId");
        String userName= (String) session.getAttribute("userName");
        String imageName = "http://localhost:8088/furniture/img/"+newfilename;
        int row = userMapper.updateAvartar(newfilename,userId,userName);
        if(row!=1){
            return new ResponseResult(203,"上传图片失败");
        }
        return new ResponseResult(200,imageName);
    }

    @Override
    public User findUserOne(Integer userId) {
        QueryWrapper<User> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("userId",userId);
        return this.userMapper.selectOne(queryWrapper);
    }
}
